package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.SHOP.entity.Activity;
import com.burgeon.backend.SHOP.entity.Basket;
import com.burgeon.backend.SHOP.entity.Goods;
import com.burgeon.backend.SHOP.entity.Seckill;
import com.burgeon.backend.SHOP.mappers.AppActivityMapper;
import com.burgeon.backend.SHOP.mappers.BasketMapper;
import com.burgeon.backend.SHOP.mappers.GoodsMapper;
import com.burgeon.backend.SHOP.mappers.SeckillMapper;
import com.burgeon.backend.SHOP.service.AppActivityService;
import com.burgeon.backend.SHOP.service.util.MathUtil;
import com.burgeon.backend.SHOPBACKEND.entity.SevenDaysReturn;
import com.burgeon.backend.SHOPBACKEND.entity.mailActivity.Gabalnara;
import com.burgeon.backend.SHOPBACKEND.mappers.BackendActivityMapper;
import com.burgeon.backend.SHOPBACKEND.rest.QuerryMailFee;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class AppActivityServiceImpl implements AppActivityService {
    @Autowired
    private AppActivityMapper appActivityMapper;
    @Autowired
    private BasketMapper basketMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private SeckillMapper seckillMapper;
    @Autowired
    private BackendActivityMapper backendActivityMapper;

    @Override
    public SevenDaysReturn sevenDaysReturnData(String token) {

        return backendActivityMapper.SevenDaysReturnData(token);
    }

    @Override
    public HashMap getMailActivityBySeckill(String sid, String phone, String token) {
        //包邮
        //查询是否包含包邮商品
        //积分抵扣
        //通过卡号关联查询抵扣需要积分(生成订单判断积分)

        boolean mailFee = false;
        int tot = 0;
        Seckill seckill = seckillMapper.getDataById(sid);
        Goods goods = goodsMapper.getGoodsById(seckill.getGid());

        tot += Integer.parseInt(seckill.getPrice());
        if ("Y".equals(goods.getMailFee())) {
            mailFee = true;
        }

        //满金额包邮
        Gabalnara gabalnara = backendActivityMapper.findMailActivityData(token);
        if (null != gabalnara
                && "Y".equals(gabalnara.getIsUse())
                && tot >= Integer.parseInt(gabalnara.getPrice())) {
            mailFee = true;
        }

        HashMap data = new HashMap();
        if (mailFee) {
            data.put("mailFee", "B");//包邮
        } else {
            Info info = GetInfoByToken(token);
            QuerryMailFee querryMailFee = new QuerryMailFee(info.getUrl(), info.getAccount(), info.getPassword());
            try {
                String row = querryMailFee.getData(phone);
                if ("null".equals(row)) {
                    data.put("mailFee", "N");
                } else {
                    data.put("mailFee", "I");
                    data.put("integral", row);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    @Override
    public HashMap getMailActvity(String[] gids, String phone, String token) {

        //包邮
        //查询是否包含包邮商品
        //积分抵扣
        //通过卡号关联查询抵扣需要积分(生成订单判断积分)

        boolean mailFee = false;
        int tot = 0;
        for (String gid : gids) {
            Goods goods = goodsMapper.getGoodsById(gid);

            tot += Integer.parseInt(goods.getPrice());
            if ("Y".equals(goods.getMailFee())) {
                mailFee = true;
            }
        }
        //满金额包邮
        Gabalnara gabalnara = backendActivityMapper.findMailActivityData(token);
        if (null != gabalnara
                && "Y".equals(gabalnara.getIsUse())
                && tot >= Integer.parseInt(gabalnara.getPrice())) {
            mailFee = true;
        }

        HashMap data = new HashMap();
        if (mailFee) {
            data.put("mailFee", "B");//包邮
        } else {
            Info info = GetInfoByToken(token);
            QuerryMailFee querryMailFee = new QuerryMailFee(info.getUrl(), info.getAccount(), info.getPassword());
            try {
                String row = querryMailFee.getData(phone);
                if ("null".equals(row)) {
                    data.put("mailFee", "N");
                } else {
                    data.put("mailFee", "I");
                    data.put("integral", row);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    @Override
    public Activity getActvityById(String id) {
        return appActivityMapper.FindAppActivityByID(id);
    }

    @Override
    public List<Activity> getActivityByToken(String token) {
        return appActivityMapper.GetAppActivity(token);
    }

    @Override
    public HashMap calculateOrderPrice(String uid, String token, String discount, String isPlus) {
        List<Basket> baskets = basketMapper.thisVipSelectedData(uid, token);
        List<Goods> goodsData = new ArrayList<>();
        HashMap data = new HashMap();
        long totalPrice = 0;
        for (Basket basket : baskets) {
            Goods goods = goodsMapper.getGoods(basket.getGid());

            //判断plus会员
            if (!"Y".equals(isPlus)) {
                goods.setPlusPrice(null);
            }

            //计算会员价
            if ("Y".equals(goods.getIsVipPrice())) {
                goods.setVipPrice(String.valueOf(MathUtil.multiply(new BigDecimal(goods.getOriginal()), new BigDecimal(discount), 0)));
            }

            goods.setPrice(minPrice(goods.getPrice(), goods.getVipPrice(), goods.getPlusPrice()));

            totalPrice += Long.parseLong(goods.getPrice()) * Long.valueOf(basket.getNum());
            if (null != goods.getActivityId() && !"0".equals(goods.getActivityId())) {
                goods.setActivitieitem(getActvityById(goods.getActivityId()));
                for (int i = 0; i < Integer.parseInt(basket.getNum()); i++) {
                    goodsData.add(goods);
                }
            }
        }
        long transactionPrice = goodsActivity(totalPrice, goodsData);
        data.put("original", totalPrice);
        data.put("transactionPrice", transactionPrice);
        data.put("discounts", totalPrice - transactionPrice);

        return data;
    }

    /**
     * 返回最小价格
     *
     * @param value1
     * @param value2
     * @param value3
     * @return
     */
    private String minPrice(String value1, String value2, String value3) {


        int a = Integer.parseInt(value1 == null ? "2147483647" : value1);
        int b = Integer.parseInt(value2 == null ? "2147483647" : value2);
        int c = Integer.parseInt(value3 == null ? "2147483647" : value3);
        int n = a < b ? a : b; //找出a和b最大值。
        int m = n < c ? n : c;//用n和c比较。
        return String.valueOf(m);
    }

    /**
     * 计算活动价格
     *
     * @param totalPrice
     * @param goodsList
     * @return
     */
    private long goodsActivity(long totalPrice, List<Goods> goodsList) {
        System.err.println("总价=" + totalPrice);
        Set<Activity> activitySet = new HashSet<Activity>();
        for (Goods goods : goodsList) {
            if (null != goods.getActivitieitem()) {
                activitySet.add(goods.getActivitieitem());
            }
        }
        for (Activity activity : activitySet) {
            int price = 0;
            int num = 0;
            boolean discount = false;
            BigDecimal multiply;
            for (Goods goods : goodsList) {
                if (activity.getId().equals(goods.getActivityId())) {
                    price += Integer.parseInt(goods.getPrice());
                    num += 1;
                }
                //判断是否满金额/数量
                if ("1".equals(activity.getType()) && price >= Integer.parseInt(activity.getValue1())) {
                    //满足金额 总价减优惠金额 停止循环 防止二次计算同一优惠
                    totalPrice -= Integer.parseInt(activity.getValue2());
                    price = 0;//每满x元减x元
                    // break;//满x元减x元
                }
                if ("2".equals(activity.getType()) && num >= Integer.parseInt(activity.getValue1())) {
//                    BigDecimal totalPriceD = new BigDecimal(price);
//                    multiply = MathUtil.multiply(
//                            MathUtil.divide(totalPriceD, new BigDecimal(10), 0),
//                            new BigDecimal(activity.getValue2()), 0);
                    discount = true;//满x件 全部同活动商品x折
                    //totalPrice = totalPrice -  (price - multiply.intValue());//满x件 x件商品打x折

                }
            }
            if (discount) {
                BigDecimal totalPriceD = new BigDecimal(price);
                multiply = MathUtil.multiply(
                        MathUtil.divide(totalPriceD, new BigDecimal(10), 2),
                        new BigDecimal(activity.getValue2()), 0);
                totalPrice = totalPrice - (price - multiply.intValue());
            }
        }
        return totalPrice;
    }

    private Info GetInfoByToken(String token) {
        return accountMapper.GetTokenData(token);
    }
}
